package com.macro.mall.portal.controller;

import cn.hutool.core.util.StrUtil;
import com.macro.mall.common.annotation.AccessLimit;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.domain.LoginParam;
import com.macro.mall.portal.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * 会员管理Controller
 *
 * @author macro
 * @date 2018/8/3
 */
@Controller
@Api(tags = "UmsMemberController")
@Tag(name = "UmsMemberController", description = "会员登录注册管理")
@RequestMapping("/sso")
public class UmsMemberController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UmsMemberService memberService;

    @AccessLimit
    @ApiOperation("会员注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> register(@RequestParam String username,
                                         @RequestParam String password,
                                         @RequestParam String telephone,
                                         @RequestParam String authCode) {
        memberService.register(username, password, telephone, authCode);
        return CommonResult.success(null, "注册成功");
    }

    @AccessLimit
    @ApiOperation("会员登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> login(@RequestBody LoginParam loginParam) {
        if (StrUtil.isBlank(loginParam.getLoginType())) {
            return CommonResult.failed("登录方式错误，请检查后再试");
        }
        String token = memberService.login(loginParam);
        if (StrUtil.isBlank(token)) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @AccessLimit
    @ApiOperation("获取会员信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Object> info(Principal principal) {
        if (principal == null) {
            return CommonResult.unauthorized(null);
        }
        UmsMember member = memberService.getCurrentMember();
        return CommonResult.success(member);
    }

    @AccessLimit
    @ApiOperation("获取验证码")
    @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<String> getAuthCode(@RequestParam String telephone) {
        if (StrUtil.isBlank(telephone)) {
            return CommonResult.failed("手机号码不能为空");
        }
        if (StrUtil.startWith(telephone, "+")) {
            telephone = telephone.replaceAll("\\+", "");
        }
        if (StrUtil.startWith(telephone, "86")) {
            telephone = telephone.replaceAll("86", "");
        }
        if (!StrUtil.startWith(telephone, "1") || StrUtil.length(telephone) != 11) {
            return CommonResult.failed("请输入正确的手机号码");
        }

        String authCode = memberService.generateAuthCode(telephone);
        return StrUtil.isBlank(authCode) ? CommonResult.failed("获取验证码失败") : CommonResult.success(authCode, "获取验证码成功");
    }

    @AccessLimit
    @ApiOperation("会员修改密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> updatePassword(@RequestBody Map<String, String> param) {

        memberService.updatePassword(param.get("telephone"), param.get("password"), param.get("authCode"));
        return CommonResult.success(null, "密码修改成功");
    }


    @AccessLimit
    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Object> refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = memberService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }
}
